package com.petalsgroup.petals.web.servlet.admin;

import com.petalsgroup.petals.pojo.AnimationDetailedDO;
import com.petalsgroup.petals.pojo.AnimationDetailedVO;
import com.petalsgroup.petals.pojo.AnimationSimpleDO;
import com.petalsgroup.petals.pojo.ResultInfo;
import com.petalsgroup.petals.service.animation.AnimationService;
import com.petalsgroup.petals.service.animation.impl.AnimationServiceImpl;
import com.petalsgroup.petals.util.RecentlyUtil;
import com.petalsgroup.petals.web.BaseServlet;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

@WebServlet("/adminAnim/*")
public class AnimationManagementServlet extends BaseServlet {
    private AnimationService animationService = new AnimationServiceImpl();

    /**
     * 修改动漫信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @author zqm
     */
    public void updateAnim(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        AnimationDetailedVO avo = new AnimationDetailedVO();
        AnimationSimpleDO simple = new AnimationSimpleDO();
        AnimationDetailedDO detailed = new AnimationDetailedDO();
        avo.setAnimationSimple(simple);
        avo.setAnimationDatailed(detailed);
        // 创建工厂
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        // 使用工厂创建解析器对象
        ServletFileUpload fileUpload = new ServletFileUpload(dfif);
        try {
            // 使用解析器对象解析request，得到FileItem列表
            List<FileItem> list = fileUpload.parseRequest(req);
            // 遍历所有表单项
            for(FileItem fileItem : list) {
                if(!fileItem.isFormField()) {
                    //如果当前表单项不是普通表单项，说明就是文件字段
                    String name = fileItem.getName();//获取上传文件的名称
                    // 如果上传的文件名称为空，即没有指定上传文件
                    if(name == null || name.isEmpty()) {
                        continue;
                    }

                    // 将in中的数据拷贝到服务器上
                    String path = this.getServletContext().getRealPath("public/cover_img");
                    path = path + "/" + UUID.randomUUID() + name;
                    InputStream is = fileItem.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    FileOutputStream fos = new FileOutputStream(path);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    byte[] b = new byte[1024];
                    int len = 0;
                    while ((len = bis.read(b)) > 0) {
                        bos.write(b, 0, len);
                    }
                    // 通过uploads目录和文件名称来创建File对象
                    // 把上传文件保存到指定位置
                    // 打印上传文件的名称
                     simple.setCover_img(path.substring(path.indexOf("\\public")));

//                    simple.setCover_img(path.substring(path.indexOf("public") - 1));

                    bos.close();
                    bis.close();
                    is.close();
                    fos.close();
                } else {
                    switch (fileItem.getFieldName()) {
                        case "aid":
                            simple.setAid(Integer.valueOf(fileItem.getString("utf-8")));
                            detailed.setAid(Integer.valueOf(fileItem.getString("utf-8")));
                            break;
                        case "aname":
                            simple.setAname(fileItem.getString("utf-8"));
                            break;
                        case "aname_jp":
                            simple.setAname_jp(fileItem.getString("utf-8"));
                            break;
                        case "flash_time":
                            simple.setFlash_time(fileItem.getString("utf-8"));
                            break;
                        case "state":
                            simple.setState(fileItem.getString("utf-8"));
                            break;
                        case "create_time":
                            simple.setCreate_time(RecentlyUtil.getDate(fileItem.getString("utf-8").replace("T"," ")));
                            break;
                        case "author":
                            simple.setAuthor(fileItem.getString("utf-8"));
                            break;
                        case "cid":
                            simple.setCid(Integer.valueOf(fileItem.getString("utf-8")));
                            break;
                        case "simpl_introduce":
                            simple.setSimple_introduce(fileItem.getString("utf-8"));
                            break;
                        case "production_company":
                            simple.setProduction_company(fileItem.getString("utf-8"));
                            break;
                        case "pv":
                            detailed.setPv(fileItem.getString("utf-8"));
                            break;
                        case "detailed":
                            detailed.setDetailed(fileItem.getString("utf-8"));
                            break;
                        case "num":
                            detailed.setNum(Integer.valueOf(fileItem.getString("utf-8")));
                            break;
                    }
                }
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            animationService.updateAnimation(avo);
            resp.sendRedirect(req.getContextPath() + "/admin/animationAdmin");
        }
    }

    /**
     * 添加动漫信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @author zqm
     */
    public void addAnim(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        AnimationDetailedVO avo = new AnimationDetailedVO();
        AnimationSimpleDO simple = new AnimationSimpleDO();
        AnimationDetailedDO detailed = new AnimationDetailedDO();
        avo.setAnimationSimple(simple);
        avo.setAnimationDatailed(detailed);
        // 创建工厂
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        // 使用工厂创建解析器对象
        ServletFileUpload fileUpload = new ServletFileUpload(dfif);
        try {
            // 使用解析器对象解析request，得到FileItem列表
            List<FileItem> list = fileUpload.parseRequest(req);
            // 遍历所有表单项
            for(FileItem fileItem : list) {
                if(!fileItem.isFormField()) {
                    //如果当前表单项不是普通表单项，说明就是文件字段
                    String name = fileItem.getName();//获取上传文件的名称
                    // 如果上传的文件名称为空，即没有指定上传文件
                    if(name == null || name.isEmpty()) {
                        continue;
                    }

                    // 将in中的数据拷贝到服务器上
                    String path = this.getServletContext().getRealPath("/public/cover_img");
                    path = path + "/" + UUID.randomUUID() + name;
                    InputStream is = fileItem.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    FileOutputStream fos = new FileOutputStream(path);
                    BufferedOutputStream bos = new BufferedOutputStream(fos);
                    byte[] b = new byte[1024];
                    int len = 0;
                    while ((len = bis.read(b)) > 0) {
                        bos.write(b, 0, len);
                    }
                    // 通过uploads目录和文件名称来创建File对象
                    // 把上传文件保存到指定位置
                    // 打印上传文件的名称

                    simple.setCover_img(path.substring(path.indexOf("\\public")));
//                    simple.setCover_img(path.substring(path.indexOf("public") - 1));
                    bos.close();
                    bis.close();
                    is.close();
                    fos.close();
                } else {
                    switch (fileItem.getFieldName()) {
                        case "aname":
                            simple.setAname(fileItem.getString("utf-8"));
                            break;
                        case "aname_jp":
                            simple.setAname_jp(fileItem.getString("utf-8"));
                            break;
                        case "flash_time":
                            System.out.println(fileItem.getString("utf-8"));
                            simple.setFlash_time(fileItem.getString("utf-8"));
                            break;
                        case "state":
                            simple.setState(fileItem.getString("utf-8"));
                            break;
                        case "create_time":
                            simple.setCreate_time(RecentlyUtil.getDate(fileItem.getString("utf-8").replace("T"," ")));
                            break;
                        case "author":
                            simple.setAuthor(fileItem.getString("utf-8"));
                            break;
                        case "cid":
                            simple.setCid(Integer.valueOf(fileItem.getString("utf-8")));
                            break;
                        case "simpl_introduce":
                            simple.setSimple_introduce(fileItem.getString("utf-8"));
                            break;
                        case "production_company":
                            simple.setProduction_company(fileItem.getString("utf-8"));
                            break;
                        case "pv":
                            detailed.setPv(fileItem.getString("utf-8"));
                            break;
                        case "detailed":
                            detailed.setDetailed(fileItem.getString("utf-8"));
                            break;
                        case "num":
                            detailed.setNum(Integer.valueOf(fileItem.getString("utf-8")));
                            break;
                    }
                }
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            simple.setPeople_num(0);
            simple.setScore(0F);
            animationService.insertAnimation(avo);
            resp.sendRedirect(req.getContextPath() + "/admin/animationAdmin");
        }
    }

    /**
     * 删除动漫信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     * @author zqm
     */
    public void deleteAnim(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String parameter = req.getParameter("aid");
        int aid = Integer.parseInt(parameter);
        boolean flag = animationService.deleteAnimation(aid);
        ResultInfo info = new ResultInfo();
        info.setFlag(flag);
        writeValue(resp, info);
    }

    @Test
    public void test(){
        String path = "E:\\Java\\MyJavaProject\\MyProject\\petals\\target\\petals-1.0-SNAPSHOT\\public\\cover_img";
        System.out.println(path.substring(path.indexOf("\\public")));
    }
}
